<template>
  <div class="message-management">
    <h2>{{ $t('message.messageManagement') }}</h2>
    
    <div class="message-filters">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select 
            v-model="filter.messageType" 
            :placeholder="$t('message.messageType')" 
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="type in messageTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select 
            v-model="filter.isRead" 
            :placeholder="$t('message.readStatus')" 
            clearable
            style="width: 100%"
          >
            <el-option :label="$t('message.read')" value="true" />
            <el-option :label="$t('message.unread')" value="false" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input 
            v-model="filter.receiverId" 
            :placeholder="$t('message.receiverId')" 
            clearable
          />
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="loadMessages">{{ $t('message.search') }}</el-button>
          <el-button @click="resetFilters">{{ $t('message.reset') }}</el-button>
        </el-col>
      </el-row>
    </div>
    
    <div class="message-actions">
      <el-button type="primary" @click="openSendMessageDialog">{{ $t('message.sendMessage') }}</el-button>
    </div>
    
    <el-table
      :data="messages"
      style="width: 100%"
      :default-sort="{ prop: 'createdAt', order: 'descending' }"
    >
      <el-table-column prop="title" :label="$t('message.title')" width="200" show-overflow-tooltip align="left" header-align="left" />
      <el-table-column prop="senderId" :label="$t('message.senderId')" width="120" align="left" header-align="left" />
      <el-table-column prop="receiverId" :label="$t('message.receiverId')" width="120" align="left" header-align="left" />
      <el-table-column prop="messageType" :label="$t('message.type')" width="120" align="left" header-align="left">
        <template #default="scope">
          <el-tag :type="getMessageTypeTag(scope.row.messageType)">
            {{ getMessageTypeLabel(scope.row.messageType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isRead" :label="$t('message.readStatus')" width="100" align="left" header-align="left">
        <template #default="scope">
          <el-tag :type="scope.row.isRead ? 'success' : 'warning'">
            {{ scope.row.isRead ? $t('message.read') : $t('message.unread') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" :label="$t('message.createdAt')" width="180" align="left" header-align="left">
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.actions')" width="200" align="left" header-align="left">
        <template #default="scope">
          <el-button size="small" @click="viewMessage(scope.row)">{{ $t('message.view') }}</el-button>
          <el-button 
            size="small" 
            :type="scope.row.isRead ? 'info' : 'primary'"
            @click="toggleReadStatus(scope.row)"
          >
            {{ scope.row.isRead ? $t('message.markUnread') : $t('message.markRead') }}
          </el-button>
          <el-button size="small" type="danger" @click="deleteMessage(scope.row.messageId)">{{ $t('message.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      style="margin-top: 20px; text-align: right;"
    />
    
    <!-- 查看消息对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="viewDialogVisible"
      width="600px"
    >
      <div class="message-detail">
        <h3>{{ currentMessage.title }}</h3>
        <div class="message-meta">
          <p><strong>{{ $t('message.sender') }}:</strong> {{ currentMessage.senderId }}</p>
          <p><strong>{{ $t('message.receiver') }}:</strong> {{ currentMessage.receiverId }}</p>
          <p><strong>{{ $t('message.type') }}:</strong> {{ getMessageTypeLabel(currentMessage.messageType) }}</p>
          <p><strong>{{ $t('message.sentAt') }}:</strong> {{ formatDate(currentMessage.createdAt) }}</p>
        </div>
        <div class="message-content">
          <p>{{ currentMessage.content }}</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="viewDialogVisible = false">{{ $t('message.close') }}</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 发送消息对话框 -->
    <el-dialog
      :title="sendDialogTitle"
      v-model="sendDialogVisible"
      width="600px"
    >
      <el-form :model="messageForm" :rules="messageRules" ref="messageFormRef" label-width="100px">
        <el-form-item :label="$t('message.receiverId')" prop="receiverId">
          <el-input 
            v-model="messageForm.receiverId" 
            :placeholder="$t('message.pleaseEnterReceiverId')"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.type')" prop="messageType">
          <el-select v-model="messageForm.messageType" :placeholder="$t('message.pleaseSelectMessageType')" style="width: 100%">
            <el-option
              v-for="type in messageTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('message.title')" prop="title">
          <el-input 
            v-model="messageForm.title" 
            :placeholder="$t('message.pleaseEnterTitle')"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.content')" prop="content">
          <el-input 
            v-model="messageForm.content" 
            type="textarea"
            :rows="5"
            :placeholder="$t('message.pleaseEnterContent')"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="sendDialogVisible = false">{{ $t('message.cancel') }}</el-button>
          <el-button type="primary" @click="sendMessage">{{ $t('message.send') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/stores/auth';

export default {
  name: 'MessageManagement',
  setup() {
    const { t } = useI18n();
    const authStore = useAuthStore();
    
    // 消息数据
    const messages = ref([]);
    
    // 筛选条件
    const filter = reactive({
      messageType: '',
      isRead: '',
      receiverId: ''
    });
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    });
    
    // 查看消息对话框
    const viewDialogVisible = ref(false);
    const dialogTitle = ref('');
    const currentMessage = ref({});
    
    // 发送消息对话框
    const sendDialogVisible = ref(false);
    const sendDialogTitle = ref('');
    
    // 消息表单数据
    const messageForm = reactive({
      receiverId: '',
      messageType: 'PERSONAL',
      title: '',
      content: ''
    });
    
    const messageFormRef = ref();
    
    // 选项数据
    const messageTypes = ref([
      { value: 'NOTICE', label: t('message.notice') },
      { value: 'PERSONAL', label: t('message.personalMessage') },
      { value: 'SYSTEM', label: t('message.systemMessage') }
    ]);
    
    // 表单验证规则
    const messageRules = {
      receiverId: [
        { required: true, message: t('message.pleaseEnterReceiverId'), trigger: 'blur' }
      ],
      title: [
        { required: true, message: t('message.pleaseEnterTitle'), trigger: 'blur' },
        { max: 255, message: t('message.titleTooLong'), trigger: 'blur' }
      ],
      content: [
        { required: true, message: t('message.pleaseEnterContent'), trigger: 'blur' },
        { max: 1000, message: t('message.contentTooLong'), trigger: 'blur' }
      ]
    };
    
    // 获取消息列表
    const loadMessages = async () => {
      try {
        // 构建查询参数
        const params = new URLSearchParams();
        params.append('page', pagination.currentPage);
        params.append('size', pagination.pageSize);
        
        if (filter.messageType) params.append('messageType', filter.messageType);
        if (filter.isRead !== '') params.append('isRead', filter.isRead);
        if (filter.receiverId) params.append('receiverId', filter.receiverId);
        
        const response = await fetch(`/api/admin/messages?${params.toString()}`, {
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          const data = await response.json();
          messages.value = data.items || data;
          pagination.total = data.total || messages.value.length;
        } else {
          ElMessage.error(t('message.failedToLoadMessages'));
        }
      } catch (error) {
        console.error('Error loading messages:', error);
        ElMessage.error(t('message.failedToLoadMessages'));
      }
    };
    
    // 重置筛选条件
    const resetFilters = () => {
      filter.messageType = '';
      filter.isRead = '';
      filter.receiverId = '';
      pagination.currentPage = 1;
      loadMessages();
    };
    
    // 查看消息
    const viewMessage = (message) => {
      currentMessage.value = { ...message };
      dialogTitle.value = message.title;
      viewDialogVisible.value = true;
      
      // 如果消息未读，标记为已读
      if (!message.isRead) {
        markMessageAsRead(message.messageId);
      }
    };
    
    // 标记消息为已读/未读
    const toggleReadStatus = async (message) => {
      try {
        const newReadStatus = !message.isRead;
        const actionText = newReadStatus ? t('message.markRead') : t('message.markUnread');
        
        const response = await fetch(`/api/admin/messages/${message.messageId}/read-status`, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ isRead: newReadStatus })
        });
        
        if (response.ok) {
          ElMessage.success(`${actionText}${t('message.successSuffix')}`);
          loadMessages(); // 重新加载消息
        } else {
          ElMessage.error(`${actionText}${t('message.failureSuffix')}`);
        }
      } catch (error) {
        console.error('Error toggling read status:', error);
        ElMessage.error(t('message.operationFailed'));
      }
    };
    
    // 标记消息为已读（用于自动标记）
    const markMessageAsRead = async (messageId) => {
      try {
        const response = await fetch(`/api/admin/messages/${messageId}/read-status`, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ isRead: true })
        });
        
        if (response.ok) {
          // 更新本地消息状态
          const msg = messages.value.find(m => m.messageId === messageId);
          if (msg) {
            msg.isRead = true;
          }
        }
      } catch (error) {
        console.error('Error marking message as read:', error);
      }
    };
    
    // 删除消息
    const deleteMessage = async (messageId) => {
      try {
        await ElMessageBox.confirm(
          t('message.confirmDeleteMessage'),
          t('message.warning'),
          {
            confirmButtonText: t('message.confirm'),
            cancelButtonText: t('message.cancel'),
            type: 'warning'
          }
        );
        
        const response = await fetch(`/api/admin/messages/${messageId}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          ElMessage.success(t('message.deleteMessageSuccess'));
          loadMessages(); // 重新加载消息
        } else {
          ElMessage.error(t('message.deleteMessageFailed'));
        }
      } catch (error) {
        console.error('Error deleting message:', error);
      }
    };
    
    // 打开发送消息对话框
    const openSendMessageDialog = () => {
      sendDialogTitle.value = t('message.sendMessage');
      resetMessageForm();
      sendDialogVisible.value = true;
    };
    
    // 重置消息表单
    const resetMessageForm = () => {
      Object.assign(messageForm, {
        receiverId: '',
        messageType: 'PERSONAL',
        title: '',
        content: ''
      });
    };
    
    // 发送消息
    const sendMessage = async () => {
      try {
        await messageFormRef.value.validate();
        
        const response = await fetch('/api/admin/messages', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(messageForm)
        });
        
        if (response.ok) {
          ElMessage.success(t('message.sendMessageSuccess'));
          sendDialogVisible.value = false;
          loadMessages(); // 重新加载消息
        } else {
          const errorData = await response.json();
          ElMessage.error(errorData.message || t('message.sendMessageFailed'));
        }
      } catch (error) {
        console.error('Error sending message:', error);
        ElMessage.error(t('message.sendMessageFailed'));
      }
    };
    
    // 获取消息类型标签
    const getMessageTypeLabel = (messageType) => {
      const type = messageTypes.value.find(t => t.value === messageType);
      return type ? type.label : messageType;
    };
    
    // 获取消息类型标签类型
    const getMessageTypeTag = (messageType) => {
      switch (messageType) {
        case 'NOTICE': return 'warning';
        case 'PERSONAL': return 'primary';
        case 'SYSTEM': return 'info';
        default: return 'primary';
      }
    };
    
    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleString();
    };
    
    // 分页处理
    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      pagination.currentPage = 1;
      loadMessages();
    };
    
    const handleCurrentChange = (page) => {
      pagination.currentPage = page;
      loadMessages();
    };
    
    onMounted(() => {
      loadMessages();
    });
    
    return {
      messages,
      filter,
      pagination,
      viewDialogVisible,
      dialogTitle,
      currentMessage,
      sendDialogVisible,
      sendDialogTitle,
      messageForm,
      messageFormRef,
      messageRules,
      messageTypes,
      loadMessages,
      resetFilters,
      viewMessage,
      toggleReadStatus,
      deleteMessage,
      openSendMessageDialog,
      sendMessage,
      formatDate,
      getMessageTypeLabel,
      getMessageTypeTag,
      handleSizeChange,
      handleCurrentChange
    };
  }
};
</script>

<style scoped>
.message-management {
  padding: 20px;
}

.message-filters {
  margin-bottom: 20px;
}

.message-actions {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}

.message-detail {
  max-height: 500px;
  overflow-y: auto;
}

.message-meta {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.message-content {
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}
</style>